/*
 * @Description:
 * @Version: 2.0
 * @Autor: zhangjx
 * @Date: 2023-05-25 14:17:19
 * @LastEditors: uphldjx 1373577124@qq.com
 * @LastEditTime: 2024-07-27 18:13:45
 */
import router from '@/router'
import { useRouterStore } from '@/stores/router'
import { useUserStore } from '@/stores/user'
import { close, start } from '@/utils/nprogress'
import { getStore } from '@/utils/store'
import { useCommonStore } from '@/stores/common'
import { isNewVersion } from '@/utils/version'

const whiteList = ['/user/login', '/sso', '/sso-token','/datav', '/demo', '/demo/table', '/404']
let hasRoles = true
router.beforeEach(async (to, from, next) => {
	isNewVersion()
	start()
	const { setMoreSearch } = useCommonStore()
	setMoreSearch({})
	const access_token = getStore('access_token')
	if (whiteList.includes(to.path)) {
		next()
	} else if (access_token) {
		if (to.name == 'userLogin') {
			next({ path: '/' })
		} else {
			const useRouter = useRouterStore()
			const user = useUserStore()
			user.LoadBreadcrumb(to)
			if (hasRoles) {
				await useRouter.LoadRecRoute(router)
				next({ ...to, replace: true })
				hasRoles = false
			} else {
				next()
			}
		}
	} else {
		next({ name: 'userLogin' })
	}
})

// router.onError((error, to) => {
// 	if (error.message.includes('Failed to fetch dynamically imported module')) {
// 		window.location.href = import.meta.env.BASE_URL + '#'+to.fullPath
// 	}
// })

router.afterEach((to) => {
	close()
	window.scrollTo(0, 0)
	// 更改标题
	let { title } = to.meta
	title = typeof title === 'function' ? title(to) : title
	if (title) {
		document.title = title as string
	}
})
